import cv2
import os

cap = cv2.VideoCapture("1.mp4")
frame_count = 0
fps = int(cap.get(cv2.CAP_PROP_FPS))
interval_frames = fps // 2 # 每秒保存一帧

# 创建输出目录
os.makedirs("out", exist_ok=True)

# 目标尺寸 (width, height)
target_size = (480, 320)

# 设置JPEG压缩参数（0-100，默认95，数值越小文件越小）
jpeg_quality = 85  # 建议在75-90之间平衡质量与体积

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    
    if frame_count % interval_frames == 0:
        # 调整图像尺寸
        resized_frame = cv2.resize(frame, target_size, interpolation=cv2.INTER_AREA)  # 推荐使用区域插值算法
        
        # 计算对应秒数
        second = frame_count // fps  
        output_path = f"out/frame_{second}sec.jpg"
        
        # 保存时应用压缩参数
        success = cv2.imwrite(output_path, resized_frame, [cv2.IMWRITE_JPEG_QUALITY, jpeg_quality])
        if not success:
            print(f"Failed to save frame {frame_count}")
    
    frame_count += 1

cap.release()